<?php
/**
 * 用户管理
 * User: Administrator
 * Time: 16:34
 */
namespace app\publics\controller;


use think\facade\Request;
use think\Db;
use thinkcms\auth\library\Tree;
use thinkcms\auth\model\Menu;

use app\common\model\UserModel;
use app\common\model\UserGradeModel;
use app\common\model\UserMsgModel;

use app\common\utils\StatusUtils;
use app\common\validate\UserAdd;
use app\service\User as UserService;

class User extends Base
{
    public $u_model;

    public function __construct()
    {
        parent::__construct();
        $this->u_model = new UserModel;
        $this->ug_model = new UserGradeModel;
        $this->um_model = new UserMsgModel;
    }

    // 会员管理
    public function index()
    {
        $param = $this->u_model->param_format(input('param.'));

        // 设置搜索条件
        $map = [];

        if (!empty($param['phone'])) {
            $map['phone'] = $param['phone'];
        }
        if ($param['type'] != -1) {
            $map['type'] = $param['type'];
        }

        $count = (int)$this->u_model->where($map)->count();
        $list  = $this->u_model
            ->where($map)
            ->order('create_time desc')
            ->paginate($param['limit'], $count);

        $select_list = [];
        foreach (StatusUtils::$usertype as $k => $v) {
            $select_list[$k] = explode('：', $v)[0];
        }

        foreach ($list as $key => $value) {
            $value['type'] = StatusUtils::user_type($value['type']);
            $value['status'] = StatusUtils::user_status($value['status']);
            $value['online'] = (new UserService)->getOnline($value['uid']);
        }

        $this->assign([
            'param' => $param,
            'list'  => $list,
            'select_list' => $select_list,
            'limit' => select_limit($param['limit']),
            'count' => $count,
            'page'  => $list->render()
        ]);

        return $this->fetch();
    }

   // 允许登录/禁止登录
    public function status_update()
    {
        $post = input('post.');

        if (empty($post['id'])) {
            $this->error('至少选择一个用户');
        }

        $data = [];
        $ids  = explode(',', $post['id']);
        foreach ($ids as $k => $v) {
            array_push($data, [
                'id' => $v,
                'status' => $post['status']
            ]);
        }
        $info = $this->u_model->saveAll($data);
        if (!empty($info)) {
            $title = $post['status'] == 0 ? '允许登录' : '禁止登录';
            $uname = $this->u_model->whereIn('id', $post['id'])->all();
            foreach ($uname as $k => $v) {
                $msg = "管理员[ {$this->username} ]给会员[ {$v['uid']} ]".$title;
                $this->auth->createLog($msg, $title);
            }
            $this->success('操作成功');
        } else {
            $this->error('操作失败，无任何数据变化');
        }
    }

    // 会员编辑
    public function edit()
    {
        $id = input('param.id');
        $u  = $this->u_model->getById($id);

        if (Request::isPost()) {
            $post = input('post.');

            $uiinfo = $this->u_model->where('id',$id)->field('password,create_time')->find();

            if($post['password'] != $uiinfo['password']){
                $time = strtotime($uiinfo['create_time']);

                $post['password'] = md5($post['password'].$time);
            }


            $ui_save = [
                'status' => $post['status'],
                'type'  => $post['type'],
                'balance'=> $post['balance'],
                'password'=> $post['password'],
            ];

            $info = $this->u_model->save($post, ['id' => $id]);
            if ($info > 0) {
                $this->auth->createLog("{$this->logname}编辑了会员[ {$u['uid']} ]的信息", '会员编辑');
                $this->success('操作成功',url('index'));
            } else {
                $this->error('操作失败');
            }
        }

        $this->assign([
            'u'  => $u,
        ]);
        return $this->fetch();
    }

    // 新增用户
    public function add()
    {
        if (Request::isPost()) {
            $post = input('post.');

            $validate = new UserAdd;
            if (!$validate->check($post)) {
                $this->error($validate->getError());
            }
            // 检测账户是否存在
            $ucount = $this->u_model
                ->where(['uid' => $post['uid']])
                ->count();
            if ($ucount > 0) {
                $this->error('账号已存在');
            }

            $time = time();
            $post['register_ip'] = get_ip();
            $post['head_img'] = mt_rand(1, 60);

            $post['balance']  = $post['balance'];
            $post['create_time'] = $time;
            $post['password']  = md5($post['password'].$time);

            $id = $this->u_model->save($post);
            if ($id > 0) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }

        return $this->fetch();
    }

    // 删除用户
    public function delete()
    {
        $post = input('param.');

        if (empty($post['id'])) {
            $this->error('至少选择一个用户');
        }

        $this->u_model->destroy($post['id']);
        $this->success('删除成功');
    }

    // 发送短信
    public function send_sms()
    {
        $ids = input('param.id');
        if (empty($ids)) {
            $this->error('至少选择一个用户');
        }

        if (Request::isPost()) {
            $sms = input('post.sms');
        }

        return $this->fetch();
    }

    //用户战绩
    public function record()
    {
        $param = input('param.');

        $param['limit'] = empty($param['limit']) ? 10 : $param['limit'];
        $param['page']  = empty($param['page']) ? 1 : $param['page'];
        // 设置搜索条件
        $map = [];

        if (!empty($param['tid'])) {
            $map['tid'] = $param['tid'];
        }

        $count = (int)$this->ug_model->list()->where($map)->count();
        $list  = $this->ug_model->list()
            ->where($map)
            ->order('create_time desc')
            ->paginate($param['limit'], $count);

        $this->assign([
            'param' => $param,
            'list'  => $list,
            'limit' => select_limit($param['limit']),
            'count' => $count,
            'page'  => $list->render()
        ]);

        return $this->fetch();
    }

    //用户消息
    public function message()
    {
        $param = input('param.');

        $param['limit'] = empty($param['limit']) ? 10 : $param['limit'];
        $param['page']  = empty($param['page']) ? 1 : $param['page'];
        // 设置搜索条件
        $map = [];

        if (!empty($param['uid'])) {
            $map['um.uid'] = $param['uid'];
        }

        $count = (int)$this->um_model->list()->where($map)->count();
        $list  = $this->um_model->list()
            ->where($map)
            ->order('create_time desc')
            ->paginate($param['limit'], $count);

        $this->assign([
            'param' => $param,
            'list'  => $list,
            'limit' => select_limit($param['limit']),
            'count' => $count,
            'page'  => $list->render()
        ]);

        return $this->fetch();
    }
}